#include "QtAnimWidget.h"

QtAnimWidget::QtAnimWidget(QGraphicsItem * parent/* = 0*/, Qt::WindowFlags wFlags/* = 0*/):
	QGraphicsProxyWidget(parent, wFlags)
{

}

QtAnimWidget::~QtAnimWidget()
{

}


void QtAnimWidget::updateAnimStep(qreal step)
{
	foreach (QtAnimStruct animStruct, mAnimList)
	{
		if (animStruct._timeLine->state() == QTimeLine::Running)
		{
			QRectF rt = boundingRect();

			QPointF trans = animStruct._stateBegin._translate + (animStruct._stateEnd._translate - animStruct._stateBegin._translate)*step;
			QVector3D rot = animStruct._stateBegin._rotate + (animStruct._stateEnd._rotate - animStruct._stateBegin._rotate)*step;
			QPointF scale = animStruct._stateBegin._scale + (animStruct._stateEnd._scale - animStruct._stateBegin._scale)*step;
			QTransform tran;
			tran.translate(rt.width()/2.0, rt.height()/2.0)
				.translate(trans.x(), trans.y())
				.rotate(rot.x(), Qt::XAxis)
				.rotate(rot.y(), Qt::YAxis)
				.rotate(rot.z(), Qt::ZAxis)
				.scale(scale.x(), scale.y())
				.translate(-rt.width()/2.0, -rt.height()/2.0);
			setTransform(tran);
		}
		
	}
}

void QtAnimWidget::createAnim(const QString& animName, const QtTransform& transBeg, const QtTransform& transEnd,
							  const QEasingCurve curve/* =QEasingCurve::Linear */, int timer/* =1000 */)
{
	QTimeLine* lineTime = new QTimeLine(timer, this);
	lineTime->setEasingCurve(curve);

	QtAnimStruct animStruct;
	animStruct._name = animName;
	animStruct._timeLine = lineTime;
	animStruct._stateBegin = transBeg;
	animStruct._stateEnd = transEnd;

	connect(lineTime, SIGNAL(valueChanged(qreal)), this, SLOT(updateAnimStep(qreal)));
	connect(lineTime, SIGNAL(finished()), this, SLOT(finishedSlot()));
	mAnimList.push_back(animStruct);
}

void QtAnimWidget::playAnim(const QString& animName, bool bForward/* = true*/)
{
	foreach(QtAnimStruct animStruct, mAnimList)
	{
		if (animStruct._name == animName)
		{
			mCurAnim = animName;
			if (bForward)
			{
				animStruct._timeLine->setDirection(QTimeLine::Forward);
			}
			else
			{
				animStruct._timeLine->setDirection(QTimeLine::Backward);
			}
			animStruct._timeLine->start();
		}
	}
}

void QtAnimWidget::finishedSlot()
{
	foreach (QtAnimStruct animStruct, mAnimList)
	{
		if(mCurAnim == animStruct._name)
		{
			if (animStruct._timeLine->direction() == QTimeLine::Forward)
			{
				emit finished(true);
			}
			else if (animStruct._timeLine->direction() == QTimeLine::Backward)
			{
				emit finished(false);
			}
		}
	}
}